package com.zang.date.protobuf.server;

import com.zang.date.protobuf.proto.SubscribeReqProto;
import com.zang.date.protobuf.proto.SubscribeRespProto;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

/**
 * @author Zhang Qiang
 * @Date 2019/7/22 17:57
 */
public class SubReqServerHandler extends ChannelHandlerAdapter {

     /**
      * 读取消息
      */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        SubscribeReqProto.SubscribeReq req = (SubscribeReqProto.SubscribeReq) msg;
        if ("LiLinFeng".equalsIgnoreCase(req.getUserName())){
            System.out.println("service accept client subscribe req : ["
                    + "userNAme:" + req.getUserName()
                    + "productName:" + req.getProductName()
                    + "address :" + req.getAddress()
                    + "]");
            ctx.writeAndFlush(resp(req.getSubReqId()));
        }
    }

     /**
      * 返回消息
      */
    public SubscribeRespProto.SubscribeResp resp(int subReqID){
        SubscribeRespProto.SubscribeResp.Builder builder = SubscribeRespProto.SubscribeResp.newBuilder();
        builder.setSubReqId(subReqID);
        builder.setRespCode(0);
        builder.setDesc("Netty book order succeed, 3 Day later, sent to the designated address");
        return builder.build();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        // 发生异常关闭链路
        ctx.close();
    }


}
